/**
 * Malsha 21/07/2014
 */
UserRegistration = new Object();

var user_id = null;
var user_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'userName', 'fullName', 'userGroupId', 'designation', 'email', 'gender', 'phone', 'password' ]
});

var ur_user_group_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'groupCode', 'groupName' ],
	proxy : {
		type : 'ajax',
		url : 'getUserGroup.action',
		reader : {
			type : 'json',
			root : 'groupDtos'
		}
	}
});

Ext.apply(Ext.form.field.VTypes, {
	password : function(val, field) {
		if (field.initialPassField) {
			var pwd = field.up('form').down('#' + field.initialPassField);
			return (val == pwd.getValue());
		}
		return true;
	},
	passwordText : 'Passwords do not match',
});

UserRegistration.getFields = function() {

	return Ext.create('Ext.form.FieldSet', {
		title : 'User Details',
		defaults : {
			anchor : '100%',
			msgTarget : 'under',
		},
		items : [ {
			xtype : 'textfield',
			fieldLabel : 'User Name<span style="color:red">*</span>',
			anchor : '50%',
			id : 'user_name',
			allowBlank : false,
			name : 'userName',
			listeners : {
				blur : function(field, The, eOpts) {
					if (user_id == null) {
						Ext.Ajax.request({
							url : 'checkUserName.action',
							params : {
								"user_name" : Ext.encode(field.getValue())
							},
							success : function(response) {
								var obj = Ext.decode(response.responseText);
								console.log(obj);
								if (obj.success)
									Ext.getCmp('userName_errorMsg').setVisible(true);
								else
									Ext.getCmp('userName_errorMsg').setVisible(false);
							}
						});
					}
				},
				focus : function(field, The, eOpts) {
					if (Ext.getCmp('userName_errorMsg').isVisible())
						Ext.getCmp('userName_errorMsg').setVisible(false);
				}
			}
		}, {
			xtype : 'label',
			forId : 'myFieldId',
			id : 'userName_errorMsg',
			style : {
				'font-size' : '12px',
				color : "red"
			},
			text : 'Someone already has that username. Try another',
			padding : '15 0 0 105',
			hidden : true
		}, {
			xtype : 'textfield',
			fieldLabel : 'Full Name',
			anchor : '60%',
			id : 'full_name',
			padding : '5 0 0 0',
			name : 'fullName'
		}, {
			xtype : 'textfield',
			fieldLabel : 'Password',
			name : 'pass',
			inputType : 'password',
			id : 'pass',
			minLength : 6,
			anchor : '50%',
			listeners : {
				focus : function(field, The, eOpts) {
					Ext.getCmp('re_pass').setValue('');
				}
			}
		}, {
			xtype : 'textfield',
			fieldLabel : 'Confirm Password<span style="color:red">*</span>',
			vtype : 'password',
			inputType : 'password',
			allowBlank : false,
			initialPassField : 'pass',
			anchor : '50%',
			id : 're_pass',
			name : 'password'
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			fieldLabel : 'Gender',
			defaultType : 'radiofield',
			items : [ {
				boxLabel : 'Male',
				name : 'gender',
				inputValue : 'M',
				id : 'gender_M',
				checked : true,
				padding : '0 25 0 0'
			}, {
				boxLabel : 'Female',
				name : 'gender',
				id : 'gender_F',
				inputValue : 'F',
				padding : '0 25 0 0'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				fieldLabel : 'Phone',
				flex : 1,
				id : 'phone',
				name : 'phone',
				maskRe : /[\d]/,
				minLength : 10,
				padding : '0 5 0 0'
			}, {
				xtype : 'textfield',
				fieldLabel : 'Email',
				flex : 1,
				id : 'email',
				vtype : 'email',
				name : 'email'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				fieldLabel : 'Designation',
				flex : 1,
				id : 'designation',
				name : 'designation',
				padding : '0 5 0 0'
			}, {
				xtype : 'combo',
				fieldLabel : 'User Group<span style="color:red">*</span>',
				flex : 1,
				id : 'user_group',
				store : ur_user_group_store,
				valueField : 'id',
				displayField : 'groupCode',
				allowBlank : false,
				msgTarget : 'under',
				name : 'userGroupId',
				tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{groupCode} - {groupName}</div>', '</tpl>'),
				displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{groupCode} - {groupName}', '</tpl>')
			} ]
		} ]
	});
};

var formpanel;
UserRegistration.getCenterPanel = function() {

	formpanel = Ext.create('Ext.form.Panel', {
		title : 'User Registration',
		bodyPadding : 20,
		autoScroll : true,
		frame : true,
		defaults : {
			labelWidth : 110,
			anchor : '65%',
		},
		items : [ {
			xtype : 'fieldcontainer',
			items : [ {
				xtype : 'triggerfield',
				width : 300,
				triggerCls : 'x-form-search-trigger',
				emptyText : 'Search User',
				id : 'user_object',
				style : 'float:right;',
				listeners : {
					specialkey : function(field, e) {
						if (e.getKey() == e.ENTER) {
							Ext.Msg.alert('HI', 'Press Enter');
						}
					}
				},
				onTriggerClick : function() {
					var window;
					Ext.Ajax.request({
						url : 'getUser.action',
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							user_store.loadRawData(obj.userDtos);
						}
					});
					if (!window) {
						window = Ext.create('Ext.window.Window', {
							title : 'User',
							height : 330,
							frame : true,
							width : 500,
							modal : true,
							constrain : true,
							resizable : false,
							layout : {
								type : 'fit'
							},
							items : [ {
								xtype : 'gridpanel',
								defaults : {
									anchor : '100%'
								},
								store : user_store,
								columns : [ {
									text : 'User Name',
									dataIndex : 'userName',
									flex : 1
								}, {
									text : 'Full Name',
									dataIndex : 'fullName',
									flex : 1
								} ],
								listeners : {
									itemdblclick : function(dv, record, item, index, e) {
										var data = record.data;
										UserRegistration.setFieldData(data);
										window.hide();
									}
								}
							} ]
						});
					}
					if (window.isVisible()) {
						window.hide();
					} else {
						window.show();
					}
				}
			} ]
		}, UserRegistration.getFields() ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				user_id = null;
				Ext.getCmp('pass').enable();
				Ext.getCmp('re_pass').setReadOnly(false);
				Ext.getCmp('save').setText('Save');
				Ext.getCmp('userName_errorMsg').setVisible(false);
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = this.up('form').getForm();
				if (form.isValid()) {
					formpanel.setLoading('Saving...');
					if (user_id == null) {
						form.url = 'addUser.action';
						form.submit({
							success : function(form, action) {
								form.reset();
								user_id = null;
								Ext.getCmp('pass').enable();
								Ext.getCmp('re_pass').setReadOnly(false);
								Ext.getCmp('save').setText('Save');
								Ext.Msg.alert('Success', 'User Saved Successfully');
								formpanel.setLoading(false);
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resultMsg);
								formpanel.setLoading(false);
							}
						});
					} else {
						form.url = 'updatUser.action';
						form.submit({
							params : {
								"user_id" : user_id,
							},
							success : function(form, action) {
								form.reset();
								user_id = null;
								Ext.getCmp('pass').enable();
								Ext.getCmp('re_pass').setReadOnly(false);
								Ext.getCmp('save').setText('Save');
								Ext.Msg.alert('Success', 'User Updated Successfully');
								formpanel.setLoading(false);
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', 'There is some error returned from the server.');
								formpanel.setLoading(false);
							}
						});
					}
				}
			}
		} ]
	});
	return formpanel;
};

UserRegistration.setFieldData = function(data) {
	var load = false;
	if (!load) {
		load = true;
		ur_user_group_store.load();
	}
	user_id = data.id;
	Ext.getCmp('user_object').setValue(data.fullName);
	if (data.gender == "F") {
		Ext.getCmp('gender_F').setValue(data.gender);
	} else {
		Ext.getCmp('gender_M').setValue(data.gender);
	}
	Ext.getCmp('pass').setValue(data.password);
	Ext.getCmp('re_pass').setValue(data.password);
	Ext.getCmp('pass').disable(true);
	Ext.getCmp('re_pass').setReadOnly(true);
	Ext.getCmp('user_name').setValue(data.userName);
	Ext.getCmp('full_name').setValue(data.fullName);
	Ext.getCmp('phone').setValue(data.phone);
	Ext.getCmp('designation').setValue(data.designation);
	Ext.getCmp('email').setValue(data.email);
	Ext.getCmp('user_group').setValue(data.userGroupId);
	Ext.getCmp('save').setText('Update');
};